package com.xiaoma.tpo.webservice;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.xiaoma.tpo.dao.PayOrderDao;
import com.xiaoma.tpo.domain.PayOrder;
import com.xiaoma.tpo.domain.User;
import com.xiaoma.tpo.dto.PayInfoVo;
import com.xiaoma.tpo.resource.TPOConstants;
import com.xiaoma.tpo.service.UserService;
import com.xiaoma.tpo.utils.TPOUtils;
import com.xiaoma.tpo.utils.UUIDUtils;

@Controller
@RequestMapping("/service/pay")
public class PayWS {
    
    private Object payInfo = null;
    private String infoUrl = TPOConstants.PAY + "/tuofu21/getAliPayInfo.action";
    private String addOrderUrl = TPOConstants.PAY + "/tuofu21/addOrder.action";
    private String findOrderUrl = TPOConstants.PAY + "/tuofu21/findOrder.action";
    
    @Autowired
    private  RestTemplate restTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private PayOrderDao payOrderDao;

    @RequestMapping(value="/info",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getPayInfo() {
        Map<String, Object> result = new HashMap<String, Object>();
        if (payInfo == null) {
            payInfo = getAliPayInfo();
        }
        result.put("payInfo", payInfo);
        return result;
    }
    
    @RequestMapping(value="/order",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getOrder(@RequestParam String orderNum) {
        Map<String, Object> result = new HashMap<String, Object>();
        JSONObject json = findOrder(orderNum);
        result.put("orderInfo", JSONObject.toBean(json.getJSONObject("result"), PayInfoVo.class));
        return result;
    }
    
    @RequestMapping(value="/addOrder",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> createOrder(@RequestHeader String token) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;
            
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        String uuid8 = UUIDUtils.getUUID8();
        JSONObject json = addOrder(uuid8);
        if (json.getInt("status") == 0) {//支付系统0代表成功（ps:跟我们的状态相反）
            String orderNum = json.getJSONObject("result").getString("orderNum");
            Integer orderStatus = json.getJSONObject("result").getInt("orderStatus");
            PayOrder payOrder = new PayOrder();
            payOrder.setOrderNum(orderNum);
            payOrder.setStatus(orderStatus);//1,已支付。 2，未支付
            payOrder.setUserId(user.getId());
            payOrder.setUuid8(uuid8);
            Date now = new Date();
            payOrder.setCreatedAt(now);
            payOrder.setUpdatedAt(now);
            payOrderDao.insert(payOrder);
            result.put("orderInfo", JSONObject.toBean(json.getJSONObject("result"), PayInfoVo.class));
        } else {
            result.put("status", 0);
            result.put("message", json.getString("message"));
        }
        userService.updateVisitTime(user);
        return result;
    }
    
    //--------------回调接口------------------------------
    @RequestMapping(value="/cbk",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> cbk(@RequestParam String id) {//支付端成功支付后回调接口，改变status=1，已支付
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            payOrderDao.updateByUUID8(id);
            result.put("status", 0);//支付端0表示成功
        } catch(Exception e) {
            result.put("status", 1);
        }
        return result;
    }
    
    
    
    //-----------------private method----------------------------------
    @Scheduled(cron="0 0 2 * * ?")//每天凌晨2点刷新一次支付信息
    private void refreshPayInfo() {
        System.out.println("refresh payinfo at:" + new Date());
        this.payInfo = getAliPayInfo();
    }
    
    private Object getAliPayInfo() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(headers);
        ResponseEntity<JSONObject> responseEntity= restTemplate.exchange(this.infoUrl, HttpMethod.POST, entity, JSONObject.class);
        JSONObject jsonObj = responseEntity.getBody();
        System.out.println("--getAliPayInfo--");
        return jsonObj;
    }
    
    private JSONObject addOrder(String id) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        ResponseEntity<JSONObject> responseEntity= restTemplate.exchange(this.addOrderUrl+"?id=" + id, HttpMethod.POST, entity, JSONObject.class);
        JSONObject jsonObj = responseEntity.getBody();
        return jsonObj;
    }
    
    private JSONObject findOrder(String orderNum) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        ResponseEntity<JSONObject> responseEntity= restTemplate.exchange(this.findOrderUrl+"?orderNum=" + orderNum, HttpMethod.POST, entity, JSONObject.class);
        JSONObject jsonObj = responseEntity.getBody();
        return jsonObj;
    }
}
